package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.common.Constants;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone) {
        // 首先判断手机号是否合法
        if (!PhoneUtil.isPhone(phone)) {
            return Result.fail("手机号格式错误");
        }

        String code = RandomUtil.randomNumbers(6);
        // 设置过期时间为验证码的有效期
        stringRedisTemplate.opsForValue()
                .set(Constants.VERIFICATION_CODE_PREFIX + phone, code, 5, TimeUnit.MINUTES);
        log.info("您的验证码为{}, 有效时间5分钟", code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        // 校验手机号
        if (!PhoneUtil.isPhone(loginForm.getPhone())) {
            return Result.fail("手机号格式错误");
        }
        // 从redis中获取验证码
        String code = stringRedisTemplate.opsForValue()
                .get(Constants.VERIFICATION_CODE_PREFIX + loginForm.getPhone());
        if (StrUtil.isBlank(code)) {
            return Result.fail("验证码已过期，请重新发送");
        }
        // 判断验证码是否正确
        if (StrUtil.isBlank(loginForm.getCode()) || !loginForm.getCode().equals(code)) {
            return Result.fail("验证码不正确，请重新输入");
        }
        // 判断用户是否存在
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class).eq(User::getPhone, loginForm.getPhone());
        User user = userMapper.selectOne(queryWrapper);
        // 不存在自动创建账号
        if (user == null) {
            user = createUserByPhone(loginForm.getPhone());
            userMapper.insert(user);
        }
        //保存用户到Redis
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        String token = UUID.randomUUID().toString();
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
        userMap.forEach((k, v) -> userMap.put(k, v.toString()));
        String key = Constants.USER_LOGIN_TOKEN_PREFIX + token;
        stringRedisTemplate.opsForHash().putAll(key, userMap);
        stringRedisTemplate.expire(key, Constants.LOGIN_USER_TTL, TimeUnit.MINUTES);

        log.info("尊敬的{}用户，欢迎回来", userDTO.getNickName());
        return Result.ok(token);
    }

    private User createUserByPhone(String phone) {
        String nickName = Constants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10);
        return new User()
                .setPhone(phone)
                .setNickName(nickName);
    }
}
